package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.order.model.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: atguigu
 * @create: 2023-09-15 14:19
 */

@RestController
@RequestMapping("/api/order")
public class OrderController {


    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 用户提交订单
     *
     * @param request
     * @param orderInfo
     * @return
     */
    @ApiOperation("用户提交订单")
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(HttpServletRequest request, @RequestBody OrderInfo orderInfo, @RequestParam("tradeNo") String tradeNo) {
        //1.获取当前用户ID
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)) {
            throw new RuntimeException(ResultCodeEnum.LOGIN_AUTH.getMessage());
        }
        //2.调用业务层提交订单，提交订单后返回订单ID
        orderInfo.setUserId(Long.valueOf(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo, tradeNo);
        return Result.ok(orderId);
    }

    /**
     * 查询当前登录用户订单列表
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderByPage(HttpServletRequest request, @PathVariable("page") int page, @PathVariable("limit") int limit) {
        //1.获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isBlank(userId)) {
            throw new RuntimeException(ResultCodeEnum.LOGIN_AUTH.getMessage());
        }
        //2.查询订单列表
        Page<OrderInfo> infoPage = new Page<>(page, limit);
        infoPage = orderInfoService.getOrderByPage(infoPage, userId);
        return Result.ok(infoPage);
    }


    /**
     * 提供给库存系统进行远程调用，完成订单拆单
     *
     * @param orderId 订单ID
     * @param wareSkuMap "[{"wareId":1,skuIds:[27]},{"wareId":2,skuIds:[31]}]"
     * @return
     */
    @ApiOperation("订单拆单接口处理")
    @PostMapping("/orderSplit")
    public String orderSplit(@RequestParam("orderId") Long orderId, @RequestParam("wareSkuMap") String wareSkuMap) {
        return orderInfoService.orderSplit(orderId, wareSkuMap);
    }
}
